from pymouse import PyMouse
import time
import win32gui
import logging
from PIL import ImageGrab
import numpy as np
from enum import Enum
import cv2
import tkinter

logging.basicConfig(level=logging.DEBUG)

# size of game window
        

def main():
    x, y = 50, 50

    pos = np.array([x, y])

    base = np.array([2, 40])

    prepare = np.array([871, 471]) + base + pos
    level1 = np.array([323, 182]) + base + pos
    level3 = np.array([308, 300]) + base + pos
    challange = np.array([720, 435]) + base + pos
    auto = np.array([50, 581]) + pos


    level_img = cv2.imread('image/levelpick.jpg', 0)
    prepare_img = cv2.imread('image/playerprepare.jpg', 0)
    fight_img = cv2.imread('image/autofight.jpg', 0)
    exp_img = cv2.imread('image/win1.jpg', 0)
    item_img = cv2.imread('image/item1.jpg', 0)
    showcase_img = cv2.imread('image/item2.jpg', 0)


    # define click 
    def pick_level(button):
        m.click(*button.tolist())
        m.click(*challange.tolist())

    def fight():
        m.click(*prepare.tolist())

    def make_auto():
        m.click(*auto.tolist())

    def click_anywhere():
        fight()

    # check status
    def hamming(img1, img2):
        w, h = 8, 8
        img1 = cv2.resize(img1, (w, h)).flat
        img2 = cv2.resize(img2, (w, h)).flat
        avg1 = np.mean(img1)
        avg2 = np.mean(img2)
        
        diff1 = (img1 < avg1).tolist()
        diff2 = (img2 < avg2).tolist()
        dist = 0
        for x1, x2 in zip(diff1, diff2):
            if x1 != x2:
                dist += 1
        return dist

    def check_area(img1, img2, area):
        x, y, w, h = area
        dist = hamming(img1[y:y+h, x:x+w], img2[y:y+h, x:x+w])
        logging.debug(dist)
        return dist < 10

    def is_level_select(screen):
        area = (419, 148, 138, 31)
        return check_area(screen, level_img, area)

    def is_prepare(screen):
        area = (831, 463, 99, 69)
        return check_area(screen, prepare_img, area)

    def is_auto(screen):
        area = (41, 574, 19, 16)
        return check_area(screen, fight_img, area)

    def is_exp(screen):
        area = (297, 113, 141, 125)
        return check_area(screen, exp_img, area)

    def is_item(screen):
        area = (430, 335, 99, 71)
        return check_area(screen, item_img, area)

    def is_item_showcase(screen):
        area = (429, 335, 98, 69)
        return check_area(screen, showcase_img, area)

    def is_fight_helper(screen):
        area = (74, 49, 24, 19)
        return check_area(screen, fight_img, area)

    def is_fight(screen):
        return is_auto(screen) or is_fight_helper(screen)

    STAT = Enum('STAT', 'level prepare fight exp item showcase idle')

    def check_state(screen):
        if is_level_select(screen):
            logging.debug("level")
            return STAT.level
        elif is_prepare(screen):
            logging.debug("prepare")
            return STAT.prepare
        elif is_fight(screen):
            logging.debug("fight")
            return STAT.fight
        elif is_exp(screen) or is_item(screen) or is_item_showcase(screen):
            logging.debug("finish")
            return STAT.exp
        else:
            return STAT.idle

    def finish_fighting():
        pass

    m = PyMouse()

    loop = True
    
    
    hmumu = win32gui.FindWindow('Qt5QWindowIcon', '网易MuMu')
    left, top, right, down = win32gui.GetWindowRect(hmumu)
    width, height = right-left, down-top
    win32gui.MoveWindow(hmumu, x, y, width, height, 1)
    try:
        win32gui.SetForegroundWindow(hmumu)
    except:
        pass
    # defult auto fight
    checkauto = True
    stat = STAT.level
    while loop:
        screen = np.array(ImageGrab.grab((x, y, x + width, y + height)))
        screen = cv2.cvtColor(screen[:,:,::-1], cv2.COLOR_RGB2GRAY)
        
        if stat == STAT.level:
            logging.debug("check level")
            if is_level_select(screen):
                pick_level(level3)
            else:
                stat = STAT.idle
        elif stat == STAT.prepare:
            if is_prepare(screen):
                fight()
            else:
                stat = STAT.idle
        elif stat == STAT.fight:
            if checkauto and not is_auto(screen):
                logging.debug("not auto?")
                make_auto()
                click_anywhere()
            else:
                logging.debug("is auto")
                checkauto = False
                click_anywhere()
                time.sleep(5)
            if not checkauto and not is_auto(screen):
                logging.debug("finish?")
                stat = STAT.idle
        elif stat == STAT.exp:
            if is_exp(screen) or is_item(screen) or is_item_showcase(screen):
                click_anywhere()
            else:
                stat = STAT.idle
        elif stat == STAT.idle:
            if is_level_select(screen):
                stat = STAT.level
            else:
                click_anywhere()
                stat = check_state(screen)

            if stat == STAT.idle:
                time.sleep(5)

        time.sleep(2)

    
if __name__ == '__main__':
    main()
    # start
